from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.parsers import MultiPartParser, FormParser, JSONParser
from django.db.models import Q

from .models import KnowledgeBase, Tag, Document, DocumentChunk
from .serializers import (
    KnowledgeBaseSerializer,
    TagSerializer,
    DocumentSerializer,
    DocumentChunkSerializer,
    DocumentUploadSerializer
)
from .tasks import process_document_task


class KnowledgeBaseViewSet(viewsets.ModelViewSet):
    """知识库视图集"""
    serializer_class = KnowledgeBaseSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return KnowledgeBase.objects.filter(user=self.request.user)

    @action(detail=False, methods=['get'])
    def default(self, request):
        """获取默认知识库"""
        kb = self.get_queryset().filter(is_default=True).first()
        if not kb:
            # 如果没有默认知识库，创建一个
            kb = KnowledgeBase.objects.create(
                user=request.user,
                name='我的知识库',
                description='默认知识库',
                is_default=True
            )
        serializer = self.get_serializer(kb)
        return Response(serializer.data)

    @action(detail=True, methods=['post'])
    def set_default(self, request, pk=None):
        """设置为默认知识库"""
        kb = self.get_object()
        KnowledgeBase.objects.filter(user=request.user, is_default=True).update(is_default=False)
        kb.is_default = True
        kb.save()
        return Response({'message': '已设置为默认知识库'})


class TagViewSet(viewsets.ModelViewSet):
    """标签视图集"""
    serializer_class = TagSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return Tag.objects.filter(user=self.request.user)


class DocumentViewSet(viewsets.ModelViewSet):
    """文档视图集"""
    serializer_class = DocumentSerializer
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser, JSONParser]

    def get_queryset(self):
        queryset = Document.objects.filter(user=self.request.user)

        # 按知识库筛选
        kb_id = self.request.query_params.get('knowledge_base')
        if kb_id:
            queryset = queryset.filter(knowledge_base_id=kb_id)

        # 按标签筛选
        tag_id = self.request.query_params.get('tag')
        if tag_id:
            queryset = queryset.filter(tags__id=tag_id)

        # 按文件类型筛选
        file_type = self.request.query_params.get('file_type')
        if file_type:
            queryset = queryset.filter(file_type=file_type)

        # 按状态筛选
        status = self.request.query_params.get('status')
        if status:
            queryset = queryset.filter(status=status)

        # 全文搜索
        search = self.request.query_params.get('search')
        if search:
            queryset = queryset.filter(
                Q(title__icontains=search) |
                Q(content__icontains=search)
            )

        return queryset

    @action(detail=False, methods=['post'])
    def upload(self, request):
        """上传文档"""
        serializer = DocumentUploadSerializer(data=request.data)
        if serializer.is_valid():
            file_obj = serializer.validated_data['file']
            kb_id = serializer.validated_data['knowledge_base_id']
            title = serializer.validated_data.get('title', file_obj.name)
            tag_ids = serializer.validated_data.get('tag_ids', [])

            # 检查知识库是否存在
            try:
                kb = KnowledgeBase.objects.get(id=kb_id, user=request.user)
            except KnowledgeBase.DoesNotExist:
                return Response({'error': '知识库不存在'}, status=status.HTTP_404_NOT_FOUND)

            # 创建文档
            doc_serializer = DocumentSerializer(data={
                'title': title,
                'file': file_obj,
                'knowledge_base': kb.id,
                'tag_ids': tag_ids
            }, context={'request': request})

            if doc_serializer.is_valid():
                document = doc_serializer.save()

                # 异步处理文档(提取文本、向量化等)
                document.status = 'processing'
                document.error_message = None
                document.vector_indexed = False
                document.save(update_fields=['status', 'error_message', 'vector_indexed', 'updated_at'])

                try:
                    process_document_task.delay(document.id)
                except Exception:
                    # Celery 未启动时同步执行，避免上传后无反馈
                    process_document_task.apply(args=(document.id,))

                return Response({
                    'message': '文档上传成功',
                    'document': DocumentSerializer(document, context={'request': request}).data
                }, status=status.HTTP_201_CREATED)

            return Response(doc_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['get'])
    def content(self, request, pk=None):
        """获取文档内容"""
        document = self.get_object()
        return Response({
            'title': document.title,
            'content': document.content,
            'page_count': document.page_count,
            'word_count': document.word_count,
        })

    @action(detail=True, methods=['get'])
    def chunks(self, request, pk=None):
        """获取文档分块"""
        document = self.get_object()
        chunks = document.chunks.all()
        serializer = DocumentChunkSerializer(chunks, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['post'])
    def batch_delete(self, request):
        """批量删除文档"""
        doc_ids = request.data.get('ids', [])
        if not doc_ids:
            return Response({'error': '请提供文档ID列表'}, status=status.HTTP_400_BAD_REQUEST)

        count = Document.objects.filter(id__in=doc_ids, user=request.user).delete()[0]
        return Response({'message': f'已删除 {count} 个文档'})

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取文档统计信息"""
        queryset = self.get_queryset()
        return Response({
            'total_count': queryset.count(),
            'completed_count': queryset.filter(status='completed').count(),
            'processing_count': queryset.filter(status='processing').count(),
            'failed_count': queryset.filter(status='failed').count(),
            'total_size': sum(doc.file_size for doc in queryset),
            'by_type': {
                'pdf': queryset.filter(file_type='pdf').count(),
                'docx': queryset.filter(file_type='docx').count(),
                'txt': queryset.filter(file_type='txt').count(),
            }
        })
